import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    markers: [],
    list: [],
    pageSize: 20,
    pageNum: 1,
    listId: '',
    showList: true,
    statusBarHeight: '',
    navBarHeight: '',
    option2: [{
        text: '全部',
        value: '全部',
        num: ''
      },
      {
        text: '未分配',
        value: '未分配',
        num: ''
      },
      {
        text: '待跟进',
        value: '待跟进',
        num: ''
      },
      {
        text: '跟进中',
        value: '跟进中',
        num: ''
      },
      {
        text: '营销成功',
        value: '营销成功',
        num: ''
      },
      {
        text: '营销失败',
        value: '营销失败',
        num: ''
      },
      {
        text: '无需营销',
        value: '无需营销',
        num: ''
      },
    ],
    option3: [{
        text: '全部',
        value: '全部'
      },
      {
        text: '问卷未进行',
        value: 0
      },
      {
        text: '问卷已完成',
        value: 1
      },
    ],
    option4: [{
        text: '全部',
        value: '全部'
      },
      {
        text: '问卷未进行',
        value: 0
      },
      {
        text: '问卷已完成',
        value: 1
      },
    ],
    clueStatus: '全部',
    isVisit: '全部',
    isCorp: '全部',
    topInfo: '',
    total: '',
    isGj: false,
    gjObj: {},
    gjNun: 'empty',
    corpName: '',
    opType: '',
    timer: ''
  },
  closeDrop() {
    this.selectComponent('#dropMenu2').toggle(false)
    this.selectComponent('#dropMenu3').toggle(false)
    this.selectComponent('#dropMenu4').toggle(false)
  },
  toClose() {
    this.setData({
      isGj: false
    })
  },
  goDgj() {
    this.setData({
      clueStatus: '待跟进'
    })
    this.goSearch()
  },
  goback() {
    wx.navigateBack({
      delta: 1
    })
  },
  onChange(e) {
    this.setData({
      corpName: e.detail
    })
  },
  goSearch(needFresh = '') {
    this.setData({
      list: [],
      pageSize: 20,
      pageNum: 1,
      markers: [],
      selectOne: needFresh ? this.data.selectOne : '',
    })
    this.setData({
      timer: new Date().getTime()
    })
    this.getList(this.data.timer)
  },
  async upDateNum() {
    if (!this.data.listId) return
    const params = {
      listId: this.data.listId,
    }
    const res = await getApp().globalData.request_cydn(
      '/marketing/marketingCorp/selectClueStatusAndCount', params,
      "POST"
    )
    console.log(res, 'selectClueStatusAndCount');
    this.data.option2.forEach(val => {
      val.num = res.rows[0][val.text] ? res.rows[0][val.text] : 0
    })
    console.log(this.data.option2, 'this.data.option2');
    const allNum = this.data.option2.reduce((a, b) => {
      return a + b.num
    }, 0)
    this.data.option2[0].num = allNum
    this.setData({
      gjNun: res.rows[0]['待跟进'],
      option2: this.data.option2
    })
  },
  selectTab(e) {
    console.log(e.detail, 'name')
    this.setData({
      status: e.detail.title
    })
    this.setData({
      pageNum: 1,
      list: [],
      markers: [],
      selectOne: '',
      selectOneIndex: ''
    })
    // 重新初始化点
    this.getList()
  },
  goDetail(e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${this.data.selectOne.corpCredit}`,
    });
  },
  selectOne(e) {
    // const one = this.data.list.find(pre => pre.id === e.currentTarget.dataset.id)
    // if(one.showGj) {
    //   wx.showToast({
    //     title: `请先${one.showGj}`,
    //     icon: 'none'
    //   })
    //   return
    // }
    wx.setStorageSync('md_top_obj', this.data.topInfo)
    if (this.data.onlyView) {
      wx.navigateTo({
        url: `/sub_marketing/qiyezoufangdetail/qiyezoufangdetail?id=${e.currentTarget.dataset.id}`,
      });
    } else {
      wx.navigateTo({
        url: `/sub_marketing/qiyezoufangdetail/qiyezoufangdetail?id=${e.currentTarget.dataset.id}`,
      });
    }
  },
  openIsGj(e) {
    const id = e.currentTarget.dataset.fid
    const obj = this.data.list.find(pre => pre.id === id)
    this.setData({
      opType: obj.showGj,
      gjObj: obj,
      isGj: true
    })
  },
  async punch() {
    const row = this.data.gjObj
    const params = {
      id: row.id,
      opType: this.data.opType,
      corpName: row.corpName,
      corpCredit: row.corpCredit,
    }
    const res = await getApp().globalData.request_cydn(
      '/marketing/marketingList/updateMarketingRecord', params,
      "POST"
    )
    if (res.code == 200) {
      wx.showToast({
        title: '操作成功',
        icon: 'success'
      })
    } else {
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      })
    }
    // console.log(res, '跟进');
    this.upDateNum()
    this.goSearch()
  },
  onLoad(options) {
    //获取系统信息， 状态栏高度为 sysInfo['statusBarHeight'];
    let sysInfo = wx.getSystemInfoSync();
    // 胶囊信息
    let menu = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度
    let navBarHeight = (menu.top - sysInfo.statusBarHeight) * 2 + menu.height;
    console.log(sysInfo.statusBarHeight + navBarHeight);
    this.setData(({
      statusBarHeight: sysInfo.statusBarHeight,
      navBarHeight: navBarHeight
    }))
    this.setData({
      listId: options.id,
      createUser: options.createUser,
      listName: options.listName
    })
    this.upDateNum()
    this.getInfos()
    // 步骤一、常见地图实例对象
    this.mapCtx = wx.createMapContext("myMap");
    this.setData({
      pageNum: 1,
      list: [],
      markers: [],
    })
    const that = this;
    // 获取当前的位置信息
    getApp().globalData.getLocation({
      type: "gcj02",
      success(res) {
        // 获取当前的定位
        that.initInfoByCenter(res);
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    // let pages = getCurrentPages();
    // let currentPages = pages[pages.length - 1]
    // // console.log(currentPages.options, '可以获得参数')
    // if (currentPages.options.needFresh) {
    //   this.setData({})
    //   // 步骤一、常见地图实例对象
    //   this.mapCtx = wx.createMapContext("myMap");
    //   this.setData({
    //     pageNum: 1,
    //     list: [],
    //     markers: [],
    //   })
    //   const that = this;
    //   // 获取当前的位置信息
    //   getApp().globalData.getLocation({
    //     type: "gcj02",
    //     success(res) {
    //       // 获取当前的定位
    //       that.initInfoByCenter(res);
    //     },
    //   })
    // }
    this.upDateNum()
    this.goSearch(1)
  },
  // 返回到当前定位视窗
  locationBack() {
    this.mapCtx.moveToLocation();
  },
  tabList() {
    this.setData({
      showList: !this.data.showList
    })
    console.log(this.data.showList, 'showList')
  },
  markerCalloutTap(e) {
    console.log(e, 'e')
    const selectOne = this.data.list[e.markerId]
    this.setData({
      selectOne: selectOne,
      selectOneIndex: e.markerId
    })
    this.data.markers.forEach((val, index) => {
      if (index === e.markerId) {
        val.iconPath = 'https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/center-location2.png'
      } else {
        val.iconPath = 'https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png'
      }
    })
    this.setData({
      markers: this.data.markers
    })
  },
  initInfoByCenter(res) {
    //console.log(res)
    this.setData({
      // longitude: this.transMarker([res.longitude, res.latitude])[0],
      // latitude: this.transMarker([res.latitude, res.latitude])[1],
      longitude1: res.longitude,
      latitude1: res.latitude,
    });
    this.setData({
      timer: new Date().getTime()
    })
    this.getList(this.data.timer)
  },
  // 加载更多
  scrollBottom() {
    if (this.data.list.length >= this.data.total) return
    this.data.pageNum++;
    this.getList()
  },
  changeStatus(e) {
    this.setData({
      clueStatus: e.detail
    })
    this.goSearch()
  },
  changeIsVisit(e) {
    this.setData({
      isVisit: e.detail
    })
    this.goSearch()
  },
  changeIsCorp(e) {
    this.setData({
      isCorp: e.detail
    })
    this.goSearch()
  },
  async getInfos() {
    // 获取个人信息
    const params = {
      pageSize: 1,
      pageNum: 1,
      listName: this.data.listName,
      createUser: this.data.createUser,
    }
    const res = await getApp().globalData.request_cydn(
      '/marketing/marketingList/getList', params,
      "POST"
    )
    this.setData({
      topInfo: res.rows[0]
    })
    console.log(res, 'res')
  },
  async getList(timer = '') {
    if (!this.data.listId) return
    // const userInfo = wx.getStorageSync('userInfo')
    const params = {
      listId: this.data.listId,
      pageSize: 25,
      pageNum: this.data.pageNum,
      clueStatus: this.data.clueStatus === '全部' ? [] : [this.data.clueStatus],
      corpName: this.data.corpName,
      isVisit: this.data.isVisit === '全部' ? null : this.data.isVisit,
      isCorp: this.data.isCorp === '全部' ? null : this.data.isCorp
    }
    console.log({
      ...params
    }, '名单详情列表请求');
    const res = await getApp().globalData.request_cydn(
      "/marketing/marketingCorp/getAdvanceSearch", {
        ...params
      },
      "POST"
    );
    console.log(res, '名单详情列表')
    if (timer) {
      if (res.rows.length > 0 && timer === this.data.timer) {
        // 特殊处理营销状态
        res.rows.forEach(pe => {
          pe.statusStyle = this.clueStatusColor(pe.clueStatus)
          pe.showGj = this.judgeGj(pe)
        })
        this.setData({
          list: this.data.list.concat(res.rows),
          total: res.total
        })
      }
    } else {
      if (res.rows.length > 0) {
        // 特殊处理营销状态
        res.rows.forEach(pe => {
          pe.statusStyle = this.clueStatusColor(pe.clueStatus)
          pe.showGj = this.judgeGj(pe)
        })
        this.setData({
          list: this.data.list.concat(res.rows),
          total: res.total
        })
      }
    }
    // 渲染地图上的坐标点
    this.initMarkers();
  },
  clueStatusColor(clueStatus) {
    const mapColor = [{
        status: "未分配",
        bgcolor: "#FAEBE6",
        color: "#F05728",
      },
      {
        status: "营销成功",
        bgcolor: "#E3F2ED",
        color: "#3F9F71",
      },
      {
        status: "无需营销",
        bgcolor: "#E9E9E9",
        color: "#6B6B6B",
      },
      {
        status: "跟进中",
        bgcolor: "#E4EFFF",
        color: "#3282E4",
      },
      {
        status: "待跟进",
        bgcolor: "#EEE8F9",
        color: "#7B58C2",
      },
      {
        status: "营销失败",
        bgcolor: "#F6E6E1",
        color: "#C33D28",
      },
    ];
    return mapColor.find((item) => item.status === clueStatus);
  },
  judgeGj(item) {
    let showOne = ''
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo.corpRole.includes('fir_admin')) {
      if (this.data.topInfo.upDownType !== "子机构名单") {
        if (item.clueStatus === "未分配") {
          //如果已经分配到机构，不需要跟进
            showOne = '跟进'
        }
      }
    } else if (userInfo.corpRole.includes('sec_admin')) {
      if (this.data.topInfo.upDownType !== "子机构名单") {
        if (item.clueStatus === "未分配") {
          if (this.data.topInfo.upDownType === "自己添加") {
            showOne = '跟进'
          }
        } else if (item.clueStatus === "待跟进") {
          if (item.clueUserId === userInfo.userId) {
            showOne = '跟进'
          }
        }
      }
    } else if (userInfo.corpRole.includes('manager')) {
      if (this.data.topInfo.upDownType !== "子机构名单") {
        if (item.clueStatus === "未分配") {
          if (item.createUser !== userInfo.userId) {
            showOne = '认领'
          }
        } else if (item.clueStatus === "待跟进") {
          showOne = '跟进'
        }
      }
    }
    return showOne
  },
  initMarkers() {
    const markers = [];
    // console.log(JSON.stringify(this.data.list, 'list')
    this.data.list.forEach((val, index) => {
      if (val.longitude) {
        const zuobiao = this.transMarker1([val.longitude, val.latitude]);
        const longitude = zuobiao[0];
        const latitude = zuobiao[1];
        markers.push({
          id: index,
          latitude: latitude,
          longitude: longitude,
          iconPath: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png",
          width: 14,
          height: 21,
        });
      }
    });
    this.setData({
      markers: markers,
    });
    // console.log(markers, "markers");
  },

  toprodetail(e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${e.detail.corpKey}&latitude=${e.detail.latitude}&longitude=${e.detail.longitude}&distance=${''}`,
    });
  },

  // 坐标系转化
  transMarker(item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    return resae;
  },

  // 中心点坐标转化
  transMarker1(item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
    return resae;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});